package T31_T40;

import java.util.HashMap;

public class T32 {
    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
    public Node copyRandomList(Node head) {
        /*思路：1 使用哈希表构建原链表结点->新结点的映射
        * 2 遍历哈希表，构建next和random映射
        * 3 返回链表头结点*/
        if (head==null)return null;
        Node cur=head;
        HashMap<Node, Node> map = new HashMap<>();
        while (cur!=null){
            map.put(cur,new Node(cur.val));
            cur=cur.next;
        }
        cur=head;
        while (cur!=null){
            map.get(cur).next=map.get(cur.next);
            map.get(cur).random=map.get(cur.random);
            cur=cur.next;
        }
        return map.get(head);
    }
}
